package news.yp.newsproject.view.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.news.yp.baselibrary.annotation.ViewById;
import com.news.yp.baselibrary.base.BaseFragment;

import news.yp.newsproject.presenter.presenter.CenterPresenter;

import java.util.ArrayList;
import java.util.List;

import news.yp.newsproject.R;
import news.yp.newsproject.adapter.MyRecyViewAdapter;
import news.yp.newsproject.bean.ResponsePageData;
import news.yp.newsproject.bean.ResponseSectionData;
import news.yp.newsproject.presenter.presenter.NewsPresenter;
import news.yp.newsproject.view.activity.ShowDetailActivity;
import news.yp.newsproject.listener.OnItemClickListener;

public class NewsFragment extends BaseFragment<NewsPresenter> implements CenterPresenter.ViewPresenter<ResponseSectionData> {

    @ViewById(R.id.recyle_view)
    private RecyclerView mrecyclerView;
    @ViewById(R.id.refreshLayout)
    private SwipeRefreshLayout refreshLayout;

    private View view;
    private MyRecyViewAdapter adapter;
    private List<ResponsePageData.DataBean> pageData = new ArrayList<>();
    private int index = 0;
    private String pagename;
    private boolean isSlidingUpward;

    public static Fragment createInstance(String s) {
        NewsFragment newsFragment = new NewsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("pagename", s);
        newsFragment.setArguments(bundle);
        return newsFragment;
    }

    @Override
    protected void onFragmentVisibleChange(boolean b) {
        Log.e("TAG", "NEWsFragment中的回调----" + b);
        if (b) { //开始加载数据
            pagename = (String) getArguments().get("pagename");
            Log.e("TAG", "-----当前fragment的pageName是" + pagename);
            //    getPresenter().getSection();
            getPresenter().getpage(pagename, 10, ++index);
        } else { //不可见，取消加载

        }
    }

    @Override
    protected NewsPresenter createPresenter() {
        return new NewsPresenter();
    }

    @Override
    protected View setView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.news_layout, container, false);
        return view;
    }

    @Override
    protected void initData() {
        //时间成熟开始请求网络获取数据

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView() {
        List<String> titlelist = new ArrayList<>();
        titlelist.add("hha");
        List<String> imglist = new ArrayList<>();
        imglist.add("123.jpg");
        List<String> datelist = new ArrayList<>();
        titlelist.add("hha");
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mrecyclerView.setLayoutManager(layoutManager);
        adapter = new MyRecyViewAdapter(getContext(), titlelist, imglist, datelist);
        initListener();
        //分割线
        //   mrecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
        mrecyclerView.setAdapter(adapter);
        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light, android.R.color.holo_green_light);
        initRefresh();
        initshare();
    }

    private void initshare() {
//        shouCangimg.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                shouCangimg.setSelected(!shouCangimg.isSelected());
//            }
//        });
    }

    private void initRefresh() {
        mrecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当不滑动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的item Position
                    int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                    int itemCount = manager.getItemCount();

                    // 判断是否滑动到了最后一个item，并且是向上滑动
                    if (lastItemPosition == (itemCount - 1) && isSlidingUpward) {
                        //设置正在加载中
                        adapter.changeMoreStatus(1);
                        //加载更多
                        // onLoadMore();
                        Log.e("TAG", "请求服务器我要加载更多---");
                        getPresenter().getpage(pagename, 10, ++index);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
                isSlidingUpward = dy > 0;
            }
        });

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 设置可见
                refreshLayout.setRefreshing(true);
                Log.e("TAG", "你点击了下拉刷新");
                Toast.makeText(getContext(), "哼，刷新吧。反正我也不睬你。", Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                }, 1000);
                //  getPresenter().getpage(pagename,10,++index);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initListener() {
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemOnClick(View v, int position) {
                Toast.makeText(getContext(), "你点击的是" + position, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), ShowDetailActivity.class);
                intent.putExtra("page", pagename);
                intent.putExtra("id", pageData.get(position).get_id());
                startActivity(intent);
            }
        });

    }


    @Override
    public void onLoading() {
        Toast.makeText(getContext(), "开始加载数据", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError() {
        if (index != 0) {
            //  refreshLayout.setRefreshing(false);
            adapter.changeMoreStatus(2);
        } else {
            Toast.makeText(getContext(), "服务器似乎开了小车", Toast.LENGTH_SHORT).show();
        }
        //   Toast.makeText(getContext(), "加载数据失败,服务器说没有数据", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccess(ResponseSectionData responseSectionData) {
    }


    List<String> datelists = new ArrayList<>();
    List<String> imglist = new ArrayList<>();
    List<String> titlelist = new ArrayList<>();

    @Override
    public void onPageSuccess(ResponsePageData responsePageData) {
        Log.e("TAG", "进入   onPageSuccess");
        if (index != 0) {
            // refreshLayout.setRefreshing(false);
            adapter.changeMoreStatus(0);
        }

        pageData.addAll(responsePageData.getData());

        for (ResponsePageData.DataBean dataBean : responsePageData.getData()) {
            datelists.add("1234");
            imglist.add(dataBean.getImgcon());
            titlelist.add(dataBean.getTitle());
        }
        adapter.refrsh(datelists, imglist, titlelist);

    }

}
